package cn.sciento.core.observer;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.commons.collections4.CollectionUtils;

public class EventBus<T> {
  protected final String identifier;
  
  protected final List<? extends Observer<T>> observers;
  
  public EventBus(String identifier, List<? extends Observer<T>> observers) {
    this.identifier = identifier;

    this.observers = (Optional.ofNullable(observers).orElse(new ArrayList<>())).stream().sorted(Comparator.comparingInt(Observer::order))
            .collect(Collectors.toList());
  }
  
  public void notifyObservers(T target) {
    notifyObservers(null);
  }
  
  public void notifyObservers(T target, Object... args) {
    if (CollectionUtils.isEmpty(this.observers)) {
      return;
    }
    for (Observer<T> observer : this.observers) {
      observer.update(target, args);
    }
  }
  
  public String getIdentifier() {
    return this.identifier;
  }
}
